package com.qf.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 数据源工具类
 */
public class DataSourceUtils {
    //创建数据源对象
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
    //静态代码块
    static {
        Properties properties=new Properties();
        InputStream is= DataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(is);
            is.close();
            //初始化
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化连接池失败");
        }
    }

    public static DataSource getDataSource(){
        return  dataSource;
    }

    //获取连接
    public static Connection getConnection() throws Exception {
        Connection connection = threadLocal.get();
        try {
            if (connection == null){
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            throw  new RuntimeException(e);
        }
    }
    //释放所有资源
    public static  void closeAll(ResultSet rs , Statement stat ,Connection conn) throws SQLException {
        if (rs != null){
            rs.close();
        }
        if (stat != null){
            stat.close();
        }
        if (conn != null){
            if (conn.getAutoCommit()){
                conn.close();
                threadLocal.remove();
            }
        }
    }
    //开启事务
    public static void begin() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection != null){
            connection.setAutoCommit(false);
        }
    }
    public static void commit() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection != null){
            connection.commit();
        }
    }
    public static void rollback() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection != null){
            connection.rollback();
        }
    }
    public static void close() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection != null){
            connection.close();
            threadLocal.remove();
        }
    }

}
